package pl.edu.pw.elka.tinyrepo.gate.server;

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.Socket;

import pl.edu.pw.elka.tinyrepo.common.CatalogContent;
import pl.edu.pw.elka.tinyrepo.common.CatalogContentSerializer;
import pl.edu.pw.elka.tinyrepo.common.HTTPHeaderType;
import pl.edu.pw.elka.tinyrepo.common.Request;
import pl.edu.pw.elka.tinyrepo.common.RequestHandler;
import pl.edu.pw.elka.tinyrepo.common.Response;
import pl.edu.pw.elka.tinyrepo.common.StatusCode;
import pl.edu.pw.elka.tinyrepo.common.exceptions.ContentAlreadyExistException;
import pl.edu.pw.elka.tinyrepo.common.exceptions.WrongPathException;
import pl.edu.pw.elka.tinyrepo.gate.descriptor.CatalogDescriptor;
import pl.edu.pw.elka.tinyrepo.gate.descriptor.DataServerDescriptor;
import pl.edu.pw.elka.tinyrepo.gate.descriptor.Descriptor;
import pl.edu.pw.elka.tinyrepo.gate.descriptor.FileDescriptor;
import pl.edu.pw.elka.tinyrepo.gate.descriptor.RepoDescriptor;
import sun.security.provider.certpath.OCSPResponse.ResponseStatus;


/**
 * @author: Kajot
 */

class PUTRequestHandler extends GateRequestHandler {
   
   public PUTRequestHandler(RepoDescriptor desc) {
      super(desc);
   }
   
   @Override
   public void run() {
	   
      OutputStream out = null;
      
      try {
         // wyjscie do klienta
         out = incomming.getOutputStream();
         
         // sprawdzenie czy plik juz nie istnieje
         if(desc.containsFile(request.getPath()))
            throw new ContentAlreadyExistException(request.getPath()+" already exists");

         // wybranie DS na ktory pokierujemy klienta
         DataServerDescriptor dsdesc = desc.getBestDataServer();
         
         // przekierowanie na wybrany DS
         Response res = new Response(StatusCode.MOVED_PERMANENTLY);
         String hostname = dsdesc.getHostName();
         res.addHeader(HTTPHeaderType.LOCATION, hostname);
         res.write(out);
         System.out.println("Sent response: \n"+res);

         System.out.println("PUT request redirected to " + hostname);
         
      }
      
      catch (ContentAlreadyExistException e) { // plik istnieje
         e.printStackTrace();
         Response rs = new Response(StatusCode.CONFLICT);
         rs.write(out);
      }
      catch (WrongPathException e) { // podano nieistniejaca sciezke
         e.printStackTrace();
         Response rs = new Response(StatusCode.NOT_FOUND);
         rs.write(out);
      }
      catch (IOException e) {
         // cos nie tak z polaczeniem, nic nie wysylaj, wyswietl info na serwerze
         e.printStackTrace();
      }
      
      // socket jest zamykany w klasach DAVServer
   }


   @Override
   public RequestHandler copy() {
      return new PUTRequestHandler(desc);
   }
}
